package net.lesscoding.bytebuf;

import io.netty.buffer.*;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import static net.lesscoding.bytebuf.ByteBufTest.printBuf;

/**
 * @author eleven
 * @date 2024/10/28 17:34
 * @apiNote
 */
@Slf4j
public class SliceTest {

    @Test
    public void testSlice() {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
        printBuf(buffer);
        ByteBuf slice1 = buffer.slice(0, 5);
        ByteBuf slice2 = buffer.slice(5, 10);
        printBuf(slice1);
        printBuf(slice2);


        System.out.println("===========替换下标内容========");
        buffer.retain();
        slice1.setByte(0, 'A');
        printBuf(slice1);
        buffer.release();
        printBuf(slice1);
    }

    @Test
    public void duplicateTest() {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});
        printBuf(buffer);
    }

    @Test
    public void compositeTest() {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes(new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

        ByteBuf buffer2 = ByteBufAllocator.DEFAULT.buffer();
        buffer.writeBytes(new byte[]{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'});

        CompositeByteBuf compositeBuffer = ByteBufAllocator.DEFAULT.compositeBuffer();
        compositeBuffer.addComponents(true, buffer, buffer2);

        printBuf(compositeBuffer);
    }

    @Test
    public void encoderTest() throws UnsupportedEncodingException {
        String str = "测试数据1234";
        String encode = URLEncoder.encode(str, "UTF-8");
        System.out.println(encode);
        byte[] array = StandardCharsets.UTF_8.encode(str).array();
        System.out.println(new String(array));
    }

    @Test
    public void unpooledTest() {
        ByteBuf buf1 = ByteBufAllocator.DEFAULT.buffer(5);
        buf1.writeBytes(new byte[]{1,2,3,4,5});
        ByteBuf buf2 = ByteBufAllocator.DEFAULT.buffer(5);
        buf2.writeBytes(new byte[]{6,7,8,9,10});
        // 当包装 ByteBuf 个数超过一个时,底层使用了 CompositeByteBuf
        ByteBuf buf3 = Unpooled.wrappedBuffer(buf1, buf2);
        System.out.println(ByteBufUtil.prettyHexDump(buf3));

        // 也可以用来包装普通字节数组,底层也不会有拷贝操作
        ByteBuf buf4 = Unpooled.wrappedBuffer(new byte[]{1,2,3}, new byte[]{4,5, 6});
        System.out.println(buf4.getClass());
        System.out.println(ByteBufUtil.prettyHexDump(buf4));
    }
}
